package cn.cloudtogo.staros.demo.droctopusspring.login;

import cn.cloudtogo.staros.demo.droctopusspring.workflowengine.WorkflowEnginLogin;
import cn.cloudtogo.staros.demo.droctopusspring.workflowengine.WorkflowEngineResult;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Set;

@RestController
@RequestMapping("/login")
@RequiredArgsConstructor
public class LoginController {

    private final WebClient flowEngineWebClient;

    @PostMapping
    public Mono<ResponseEntity<?>> login(
            String login,
            String password
    ) {
        if (!Set.of("testA", "testB", "testC").contains(login)) {
            return Mono.just(ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("认证失败"));
        }

        if (!"123456".equals(password)) {
            return Mono.just(ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("认证失败"));
        }

        WorkflowEnginLogin workflowEnginLogin = new WorkflowEnginLogin();
        workflowEnginLogin.setBizUsername(login);
        workflowEnginLogin.setBizRealname(login);

        workflowEnginLogin.setOrgCode("001");

        workflowEnginLogin.setWfUsername("admin");
        workflowEnginLogin.setWfPassword("d2964ee5b4b30fa67fe4f7b9c4efea89");
        workflowEnginLogin.setWfRole("bizCommonUser");

        return wfLogin(workflowEnginLogin)
                .flatMap(result -> {
                    LoginResult loginResult = new LoginResult();
                    loginResult.setUserId(login);
                    loginResult.setUserRole(getRole(login));
                    loginResult.setWfJwt(result.getObj());
                    return Mono.just(ResponseEntity.ok(loginResult));
                });
    }

    private Mono<WorkflowEngineResult<String>> wfLogin(WorkflowEnginLogin workflowEnginLogin) {
        return flowEngineWebClient.post()
                .uri("/wf/login/api")
                .bodyValue(workflowEnginLogin)
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference<>() {
                });
    }

    private String getRole(String login) {
        return Set.of("testB", "testC").contains(login) ? "admin" : "user";
    }

}
